package cn.gcjxsc.controller.api;

import cn.gcjxsc.common.data.query.RedPackRecordQuery;
import cn.gcjxsc.common.data.vo.RedPackRecordVo;
import cn.gcjxsc.consts.merchant.MerchantAccountType;
import cn.gcjxsc.entity.merchant.Merchant;
import cn.gcjxsc.entity.merchant.MerchantAccount;
import cn.gcjxsc.entity.merchant.redpack.RedPackRecord;
import cn.gcjxsc.service.merchant.MerchantAccountService;
import cn.gcjxsc.service.merchant.MerchantService;
import cn.gcjxsc.service.merchant.redpack.RedPackRecordService;
import com.zgxl.common.vo.PageDataVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;

/**
 * 商户红包控制器.
 *
 * @author pumbaa
 * @since 1.0
 */
@RestController("apiRedPackController")
@RequestMapping("/api/redpack")
public class RedPackController {
    @Autowired
    private RedPackRecordService recordService;
    @Autowired
    private MerchantAccountService accountService;
    @Autowired
    private MerchantService merchantService;

    /**
     * 查询商户红包余额
     * @param id 商户id
     * @return 返回商户红包余额
     */
    @RequestMapping("/merchant/queryBalance")
    public BigDecimal queryRedPackBalance(@RequestParam("id") Integer id){
        BigDecimal balance = BigDecimal.ZERO;
        Merchant merchant = merchantService.findById(id);
        if (null != merchant) {
            MerchantAccount account = accountService.findByMerchantIdAndType(merchant, MerchantAccountType.WX_CASH.getType());
            balance = account.getAmount();
        }
        return balance;
    }

    /**
     * 查询红包列表
     * @param filter 过滤条件
     * @param page 当前页
     * @param pageSize 每页记录数
     * @return
     */
    @RequestMapping("/list")
    public PageDataVo<RedPackRecordVo> queryRedPackRecord(RedPackRecordQuery filter,
                                                          @RequestParam(value = "page", defaultValue = "1", required = false) int page,
                                                          @RequestParam(value = "pageSize", defaultValue = "30", required = false) int pageSize) {
        filter.format();
        Page<RedPackRecord> list = recordService.findList(filter, page, pageSize);
        List<RedPackRecord> records = list.getContent();
        List<RedPackRecordVo> voList = new ArrayList<>();
        for (RedPackRecord record : records) {
            voList.add(recordService.converter(record));
        }

        PageDataVo<RedPackRecordVo> pageDataVo = new PageDataVo<>();
        pageDataVo.setList(voList);
        pageDataVo.setPage(page);
        pageDataVo.setPageSize(pageSize);
        pageDataVo.setTotal(list.getTotalElements());

        return pageDataVo;
    }
}
